package jplat.core.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import jplat.base.constant.KPlatResponseCode;
import jplat.base.constant.KTraceLog;
import jplat.core.trans.JAppConnectInfo;
import jplat.tools.config.JAppConfig;
import jplat.tools.string.JLogUtils;
import jplat.tools.string.JRandomUtil;
import jplat.tools.string.StringUtil;

public class JSessionFilter implements Filter {
	
	private Logger logger = Logger.getLogger(this.getClass());
 	private Pattern[] regPatterns = new Pattern[0];
 	
 	private String loginUrl ="/linkusWeb/page/login/loginWechat.do";
 	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}
	@Override
	public void init(FilterConfig config) throws ServletException
	{
		// TODO Auto-generated method stub
		String exclude = config.getInitParameter("exclude");
 		if (StringUtil.isNotEmpty(exclude)) {
			String[] patterns = exclude.trim().split(",|;");
			regPatterns = new Pattern[patterns.length];
			for (int i = 0; i < patterns.length; i++) {
				if (StringUtil.isNotEmpty(patterns[i])) {
					regPatterns[i] = Pattern.compile(patterns[i]);
				}
			}
			logger.debug("session filter pattern size:" + regPatterns.length);
		}
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain ) throws IOException, ServletException
	{
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse rsp = (HttpServletResponse)response;
 		req.setCharacterEncoding("utf-8");
		int urlLen = 25;
		String myUrl = req.getRequestURL().toString();
		if ( myUrl.length() > urlLen )
		{
			myUrl = myUrl.substring(myUrl.length() - urlLen );
		}
		
		//请求日志会话追踪.
		String transMark = JRandomUtil.getStrongRandomSequence(13);
		String sessionMark = req.getHeader(JAppConnectInfo.H_HTOKEN_NAME);
		if ( StringUtil.isNotEmpty(sessionMark))
		{
			transMark = sessionMark+"."+transMark;
		}

		String addrInfo = StringUtil.getIpAddr(req)+":"+ req.getRemotePort();
		logger.info(JLogUtils.getStartTraceLog(KTraceLog.ACTION_RECV_APP,transMark, JLogUtils.buildUserData(myUrl,addrInfo )));
		//不检查会话交易
			 
		//匹配网页会话检测.
		if (!checkExcludeWebSession(req.getRequestURI()) && JSessionUtils.checkSessionAvail(req) == null)		{
			//request.getRequestDispatcher("/page/loginPC.do").forward(request, response);
			//rsp.sendRedirect("/dolphine/pageRc/error/sessionError.jsp");
			//return;
			response.setContentType("text/html;charset=UTF-8");
			String str = "";
			// 判断是否为ajax请求
			//String projectPath = request.getServletContext().getContextPath();
			//loginUrl = "linkusWeb" + loginUrl;
			logger.info("loginUrl:-->"+loginUrl);
			if (req.getHeader("x-requested-with") != null&& req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
				rsp.addHeader("sessionstatus", "timeOut");
				rsp.addHeader("loginPath", loginUrl);
				str = "{\"head\":{\"retCode\":\"0005\",\"retMsg\":\"会话超时，请重新登陆\"}}";
 			} else {
				str = "<script language='javascript'>"
							//+ "alert('会话过期,请重新登录');"
							+ "window.top.location.href='"
							+ loginUrl
							+ "';</script>";
				response.setContentType("text/html;charset=UTF-8");// 解决中文乱码
 			}
			try {
				PrintWriter writer = response.getWriter();
				writer.write(str);
				writer.flush();
				writer.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return ;
		} 
		
		filterChain.doFilter(request, response); 
		response.setContentType("text/html;charset=UTF-8");
		String rspCode = rsp.getHeader(JAppConnectInfo.H_RET_HEAD);
	 
		logger.info(JLogUtils.getEndTraceLog(KTraceLog.ACTION_RECV_APP, transMark, JLogUtils.buildUserData(myUrl,rspCode) ));
	}
	
	private boolean checkExcludeWebSession( String URI )
	{
		for (Pattern pattern : regPatterns)
		{
			Matcher m = pattern.matcher(URI);
			if( m.find()) return true;
		 
		}
		return false;
	}
 
}
